package com.yigo.prc.gateway.controller;

import com.yigo.framework.http.Q;
import com.yigo.framework.http.R;
import com.yigo.prc.api.category.PrcCategoryFeign;
import com.yigo.prc.api.category.command.CreateCategoryCmd;
import com.yigo.prc.api.category.resp.CategoryTreeResp;
import com.yigo.prc.app.service.PrcCategoryAppService;
import com.yigo.prc.domain.category.repo.PrcCategoryRepo;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author chenzl
 */
@RestController
public class PrcCategoryController implements PrcCategoryFeign {
    @Resource
    private PrcCategoryAppService prcCategoryAppService;
    @Resource
    private PrcCategoryRepo prcCategoryRepo;

    @Override
    public R createCategory(Q<CreateCategoryCmd> q) {
        prcCategoryAppService.createCategory(q.getNonNullParams());
        return R.ok();
    }

    @Override
    public R<List<CategoryTreeResp>> queryCategoryTree(Q q) {
        List<CategoryTreeResp> list = prcCategoryRepo.listCategory();
        List<CategoryTreeResp> lvl1List = list.stream().filter(x -> 1 == x.getPid()).collect(Collectors.toList());
        lvl1List.forEach(x -> getChildren(list, x));
        return R.ok(lvl1List);
    }

    private void getChildren(List<CategoryTreeResp> list, CategoryTreeResp parent) {
        List<CategoryTreeResp> children = list.stream().filter(x -> x.getPid().equals(parent.getId()))
                .collect(Collectors.toList());
        parent.setChildren(children);
        children.forEach(x -> getChildren(list, x));
    }
}
